# -*- coding: utf-8 -*-

import httplib


responseTable = {
	0: 'SUCCESS',
	1: 'FAILURE',
	2: 'ROBOT_BUSY',
	3: 'FEATURE_NOT_IMPLEMENTED',
	4: 'UNKNOWN_CGI_ACTION',
	5: 'NO_NS_SIGNAL',
	6: 'NO_EMPTY_PATH_AVAILABLE',
	7: 'FAILED_TO_READ_PATH',
	8: 'PATH_BASEADDRESS_NOT_INITIALIZED',
	9: 'PATH_NOT_FOUND',
	10: 'PATH_NAME_NOT_SPECIFIED',
	11: 'NOT_RECORDING_PATH',
	12: 'FLASH_NOT_INITIALIZED',
	13: 'FAILED_TO_DELETE_PATH',
	14: 'FAILED_TO_READ_FROM_FLASH',
	15: 'FAILED_TO_WRITE_TO_FLASH',
	16: 'FLASH_NOT_READY',
	17: 'NO_MEMORY_AVAILABLE',
	18: 'NO_MCU_PORT_AVAILABLE',
	19: 'NO_NS_PORT_AVAILABLE',
	20: 'NS_PACKET_CHECKSUM_ERROR',
	21: 'NS_UART_READ_ERROR',
	22: 'PARAMETER_OUTOFRANGE',
	23: 'NO_PARAMETER',
	}

class RovioError(Exception):
	def __init__(self, code):
		self.code = code
	def __str__(self):
		return responseTable[code]

class Robot(object):
	"""
		This class is the instance of the rovio.
		Others can send commands to this robot,
		it will interpret the commands and send them
		to the rovio.
	"""
	def __init__(self, address):
		""" Address is the ip address, or hostname
			of the rovio to connect to
		"""
		self.address = address

		self._conn = httplib.HTTPConnection(address)
		self._conn.connect()

		self.response = None


	def _makeURL(self, scriptName, cmd, params):
		""" Returns the url associated with the
			parameters
		"""
		url = "/" + scriptName + ".cgi?"
		if cmd:
			url += "Cmd="+cmd+"&"
		for key in params:
			url += str(key)+'='+str(params[key])+'&'

		return url


	def sendCommand(self, scriptName, cmd, params):
		""" Send a command to the robot, optionally returns a response.
			scriptName is the name of the cgi script to call on the robot
			params are the params to pass
		"""

		self.response = None
		self._conn.request("GET", self._makeURL(scriptName, cmd, params))

		resp = self._conn.getresponse()

		resp = resp.read()

		#responses = resp[resp.find("responses"):]
		#s = responses.find('=')
		#code = int(responses[s+2:responses.find(' ')])
		#if code != 0:
			#raise RovioError(code)

		self.repsonse = resp
		return resp


	def sendCommandNB(self, scriptName, params):
		""" Send a command to the robot non blocking.
			NOTE: You have to call recvResponse before you can make another
			request.
			scriptName is the name of the cgi script to call on the robot
			params are the params to pass
		"""

		self.response = None
		self._conn.request("GET", self._makeURL(scriptName, params))


	def recvResponse(self):
		""" Returns the last response.
			If you have sent a command non-blocking then this
			blocks until the response
		"""

		if not self.response:
			resp = self._conn.getresponse()
			resp = resp.read()
			self.repsonse = resp

		return self.response